<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Cropping and Merging</title>
</head>

<body>
    <form>
        <label for="imageUpload">Upload an image:</label>
        <input type="file" id="imageUpload" accept="image/*">

    </form>
    <button id="mergeButton">Merge Images</button> <!-- Add a merge button -->

    <br>
    <canvas id="resultCanvas" width="850" height="850" ></canvas>
    <canvas id="bgcanvas" width="2500" height="8820"></canvas>

</body>

</html>

<script>
    const resultCanvas = document.getElementById('resultCanvas');
    const bgcanvas = document.getElementById('bgcanvas');
    const ctx = resultCanvas.getContext('2d');
    const bgctx = bgcanvas.getContext('2d');
    const backgroundImage = new Image();
    backgroundImage.src = 'bg.jpeg';

    document.addEventListener('DOMContentLoaded', () => {
        const imageUpload = document.getElementById('imageUpload');

        imageUpload.addEventListener('change', () => {
            const imageFile = imageUpload.files[0];

            if (imageFile) {
                const reader = new FileReader();

                reader.onload = function (event) {
                    const image = new Image();

                    image.src = event.target.result;

                    image.onload = function () {
                        const canvasContext = resultCanvas.getContext('2d');
                        const sourceX = 60;
                        const sourceY = 320;
                        const sourceWidth = 850;
                        const sourceHeight = 850;
                        const destWidth = 850;
                        const destHeight = 850;
                        canvasContext.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
                        canvasContext.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, 0, 0, destWidth, destHeight);
                    };
                };

                reader.readAsDataURL(imageFile);


            }
           
        });

        const mergeButton = document.getElementById('mergeButton');
        mergeButton.addEventListener('click', () => {
            // Merge the cropped image with bg.jpeg
            bgctx.clearRect(0, 0, resultCanvas.width, resultCanvas.height);
            bgctx.drawImage(backgroundImage, 0, 0, 2500, 8820); // Draw bg.jpeg
            bgctx.drawImage(resultCanvas, 275, 7845, 850, 850); // Draw the cropped image on top

            // Now, resultCanvas contains the merged image
            // You can display it, export it, or perform further actions as needed.
        });
    });
</script>